package com.bijava.test.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.atomic.AtomicValue;
import org.apache.curator.framework.recipes.atomic.DistributedAtomicInteger;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.retry.RetryNTimes;
/**
 * @author bijava
 * @version 1.0
 * @since 20-9-18
 * 使用Curator实现分布式计数器
 * 把计数结果写入某个节点中，在分布式环境下做原子化的叠加
 */
public class DistAtomicInt {

    static String distatomicint_path = "/curator_atomicint";
    static CuratorFramework client = CuratorFrameworkFactory.builder()
            .connectString("81.71.8.200:2181")
            .retryPolicy(new ExponentialBackoffRetry(1000, 3))
            .build();

    public static void main(String[] args) throws Exception {
        client.start();
        DistributedAtomicInteger atomicInteger = new DistributedAtomicInteger(
                client,
                distatomicint_path,
                new RetryNTimes(3, 1000));
        AtomicValue<Integer> rc = atomicInteger.add(8);
        System.out.println( "Result: " + rc.postValue());
        System.out.println( "Result: " + rc.preValue() );
    }
}
